package top.zhmq.userconsumer.service;


import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.zhmq.commonmodule.model.User;
import top.zhmq.userconsumer.utils.CodeUtil;
import top.zhmq.userconsumer.utils.MailUtil;

import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author Glory
 * @classname RabbitMQService
 * @create 2021-06-02 15:09
 */

@Service
public class RabbitMQService {
    @Autowired
    MailUtil mailUtil;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * **使用基于注解的方式实现消息服务
     * 1.1、Publish/Subscribe工作模式接收，处理邮件业务
     *
     * @param user
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue("fanout_queue_email"),
            exchange = @Exchange(value = "fanout_exchange", type = "fanout")))
    public void psubConsumerEmailAno(User user) throws Exception {

        System.out.println("1邮件业务接收到消息： " + user);

        String code = CodeUtil.randomCode();
        System.out.println(code);
        mailUtil.sendAEmail(user.getUemail(), code);

        System.out.println(code);

        redisTemplate.boundValueOps("code_" + user.getUname()).set(code + "");
        redisTemplate.boundValueOps("code_" + user.getUname()).expire(15, TimeUnit.MINUTES);//设置验证码五分钟到期
    }

    /**
     * 1.2、Publish/Subscribe工作模式接收，处理短信业务
     *
     * @param user
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue("fanout_queue_sms"),
            exchange = @Exchange(value = "fanout_exchange", type = "fanout")))
    public void psubConsumerSmsAno(User user) {
        //TODO 发送短信
        System.out.println("2短信业务接收到消息： " + user);
    }

}
